/**
 * @Description:
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 29/09/24 PM1:49
 */

import { hasOwn } from 'sf-utils2'
import { ref } from 'vue'

/**
 * qiankun 子应用选择器
 */
export const QIANKUN_MICROAPP_WRAPPER_SELECTOR = `div[id^=__qiankun_microapp_wrapper][data-qiankun]`

/**
 *  微应用映射
 */
const MICRO_APP_NAME_MAP = {
  /** 权限 */
  AUTH: '/micro-auth',
  /** 流程 */
  WORKFLOW: '/micro-workflow'
} as const

/**
 *  解决微应用渲染
 *  主要是fix body渲染问题
 */
export class ObserveScopedBody {
  static body = document.body

  ob: MutationObserver

  static observeScopedBodyInstance

  nextSerialCbs = [(dom: HTMLHtmlElement) => !dom.classList.contains('ijep-message')] // 下一步方法集合

  constructor() {
    this.ob = new MutationObserver((mutationsList) => {
      // console.log('变化了', mutationsList)
      /**
       * 设置body 直接子节点属性 截流
       * @type {Function}
       */
      // const debounceSetBodySubChildListAttrs = debounce(this.setBodySubChildListAttrs.bind(this), 0)

      for (let mutation of mutationsList) {
        if (['childList', 'attributes'].includes(mutation.type)) {
          this.updateBodyChildren()
        }
      }
    })
  }

  /**
   * 更新body下直接子节点
   */
  updateBodyChildren() {
    const microAppName = this.activeQiankunMicroAppName
    window.requestAnimationFrame(() => {
      this.setBodySubChildListAttrs(microAppName)
    })
  }

  /**
   * 设置body子应用属性
   */
  setBodySubChildListAttrs(appName: string) {
    const realAppName = (appName || '').split('--').filter(Boolean).at(0)
    const children = document.body.children
    Array.from(children).forEach((item: HTMLHtmlElement) => {
      if (this.nextSerialCbs.length && !this.nextSerialCbs.every((cb) => cb(item))) return
      if (
        item?.nodeType === Node.ELEMENT_NODE &&
        ['DIV', 'SECTION'].includes(item.tagName) &&
        item.id != 'app'
        // !hasOwn(v.dataset, 'vApp')
      ) {
        if (hasOwn(item.dataset || {}, 'qiankunWrap')) {
          // 如果是qiankunWrap 包裹的
          updateDivQiankun(item)
        } else {
          const wrapDom = document.createElement('div')
          wrapDom.dataset.qiankunWrap = ''
          wrapDom.classList.add('qiankun-fake-wrapper')
          wrapDom.style.cssText = 'display: contents;'
          wrapDom.append(item)
          document.body.append(wrapDom)
          updateDivQiankun(wrapDom)
        }
      }
      function updateDivQiankun(containerDom) {
        if (!containerDom.childNodes?.length) containerDom.remove()

        function removeAttributesWithAuthV2() {
          containerDom.classList.remove('theme--tzx')
          const subChildren = Array.from(containerDom.children || [])
          subChildren.forEach((el: HTMLHtmlElement) => {
            el.removeAttribute('data-vxe-ui-theme')
            el.classList.remove('theme--tzx')
          })
        }

        function addAttributesWithAuthV2() {
          containerDom.classList.add('theme--tzx')
          // 为了修复 vxe-table 样式丢失的问题
          const subChildren = Array.from(containerDom.children || [])
          subChildren.forEach((el: HTMLHtmlElement) => {
            el.setAttribute('data-vxe-ui-theme', 'light')
            el.classList.add('theme--tzx')
          })
        }

        if (appName == 'none' || !appName) {
          // 如果appName等于none 或者 是在主应用中 就移除
          delete containerDom.dataset.qiankun
          delete containerDom.dataset.isFake
          removeAttributesWithAuthV2()
        } else {
          // 如果是权限
          if (realAppName == MICRO_APP_NAME_MAP.AUTH) {
            addAttributesWithAuthV2()
          } else {
            removeAttributesWithAuthV2()
          }
          if (appName == containerDom.dataset.qiankun) return
          containerDom.dataset.qiankun = appName
          containerDom.dataset.isFake = ''
        }
      }
    })
  }

  /**
   * 获取当前激活微应用的应用名称（乾坤内部生成的）
   * @return {Element}
   */
  get activeQiankunMicroAppName() {
    // const layoutStore = useLayoutStore()
    const stor = `.router-view-iframe__inner--active ${QIANKUN_MICROAPP_WRAPPER_SELECTOR}`
    const microAppContainer = document.querySelector(stor)
    // console.log('microAppContainer', microAppContainer)
    return microAppContainer && microAppContainer.getAttribute('data-qiankun')
  }

  start() {
    this.ob.observe(document.body, { attributes: true, childList: true, subtree: false })
  }

  stop() {
    this.ob.disconnect()
  }
}

/**
 * 生成虚假的进度 百分比逻辑
 */
export function useFakeProgress() {
  const setting = {
    trickleSpeed: 100
  }

  const progress = ref(0)
  const reset = {}

  const start = () => {
    progress.value = 0
    const work = function () {
      setTimeout(function () {
        if (progress.value >= 100) {
          progress.value = 99
          return
        }
        const tempProgress = progress.value + ~~(Math.random() * 6)
        if (tempProgress >= 99) {
          progress.value = 99
          return
        }
        progress.value = tempProgress
        work()
      }, setting.trickleSpeed)
    }
    work()
  }

  const done = () => {
    progress.value = 100
  }

  return {
    reset,
    progress,
    start,
    done
  }
}
